<!--
 * @Descripttion: 
 * @Author: liZhaoBo
 * @Date: 2024-04-30 10:14:37
 * @LastEditors: fangshengchu
 * @LastEditTime: 2024-05-30 18:45:53
-->
<template>
  <a-select
    v-model="selVal"
    v-bind="$attrs"
    placeholder="请选择"
    :loading="loading"
    :popup-container="isFullscreen ? mainBox : 'body'"
    @change="selChange"
  >
    <a-option
      v-for="item of dictList"
      :key="item.value"
      :value="item.value"
      :label="item.label"
    />
  </a-select>
</template>

<script setup lang="ts">
  import { ref, defineProps, onMounted, watch, defineEmits } from 'vue';
  import { queryDictDataRecordList } from '@/api/system/dictionary';
  import { Message } from '@arco-design/web-vue';
  import lodash from 'lodash';
  import { isFullscreen } from '@/common/hooks/full-screen';

  const emit = defineEmits(['update:modelValue', 'change']);
  const props = defineProps({
    modelValue: {
      type: String || Array,
      default: null,
    },
    dictType: {
      type: String,
      default: '',
    },
    fitVal: {
      type: Array,
      default: () => [],
    },
  });
  const loading = ref<boolean>(false);
  // const selVal = ref<string | any[]>();
  const dictList = ref<any[]>([]);
  const selVal = ref<string | string[]>();
  const mainBox = ref();
  mainBox.value = document.querySelector('main');
  watch(
    () => props.modelValue,
    (n) => {
      if (!n) {
        selVal.value = null;
      }
    }
  );

  const selChange = () => {
    emit('update:modelValue', selVal.value);
    emit(
      'change',
      lodash.cloneDeep(dictList.value.find((i) => selVal.value === i.value))
    );
  };
  // 获取字典数据
  const getDictDataRecordList = async () => {
    const params = {
      dictType: props.dictType,
    };
    loading.value = true;
    try {
      const { data } = await queryDictDataRecordList(params);
      dictList.value = data.filter((item: any) => {
        return !props.fitVal.includes(item.value);
      });
    } catch (error) {
      Message.error(`字典类型未${props.dictType}的字典数据请求失败！`);
    } finally {
      selVal.value = props.modelValue;
      loading.value = false;
    }
  };
  watch(
    () => props.modelValue,
    () => {
      if (props.modelValue) {
        selVal.value = props.modelValue;
      }
    },
    {
      immediate: true,
    }
  );
  onMounted(() => {
    getDictDataRecordList();
  });
</script>
